package com.example.text.controller;

import com.example.text.entity.News;
import com.example.text.service.NewsService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/news")
@RequiredArgsConstructor
public class NewsController {
    private final NewsService newsService;

    @PostMapping
    public ResponseEntity<?> addNews(@RequestBody News news) {
        try {
            if (news.getCreateTime() == null) {
                news.setCreateTime(LocalDateTime.now());
            }
            News savedNews = newsService.save(news);
            return ResponseEntity.ok(savedNews);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("添加失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getNewsById(@PathVariable String id) {
        try {
            Optional<News> news = newsService.findById(id);
            if (news.isPresent()) {
                return ResponseEntity.ok(news.get());
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("查询失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteNewsById(@PathVariable String id) {
        try {
            newsService.deleteById(id);
            Map<String, String> response = new HashMap<>();
            response.put("message", "删除成功");
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            if (e.getMessage().contains("文档不存在")) {
                return ResponseEntity.badRequest().body("删除失败: " + e.getMessage());
            }
            return ResponseEntity.badRequest().body("删除失败: " + e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除失败: " + e.getMessage());
        }
    }

    @GetMapping("/search")
    public ResponseEntity<?> searchNews(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "false") boolean highlight) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                List<News> allNews = newsService.findAll();
                return ResponseEntity.ok(allNews);
            } else {
                if (highlight) {
                    SearchHits<News> searchHits = newsService.search(keyword);
                    return ResponseEntity.ok(searchHits);
                } else {
                    List<News> newsList = newsService.searchWithoutHighlight(keyword);
                    return ResponseEntity.ok(newsList);
                }
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("搜索失败: " + e.getMessage());
        }
    }

    @GetMapping
    public ResponseEntity<?> getAllNews() {
        try {
            List<News> allNews = newsService.findAll();
            return ResponseEntity.ok(allNews);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("查询失败: " + e.getMessage());
        }
    }
}
